package utils

import (
	"github.com/BurntSushi/toml"
)

/**
  初始化配置
  @path 指定配置文件路径,默认./conf/config.toml
*/
func InitConfig(path string) {
	//默认去程序根目录，查找配置文件
	if path == "" {
		path = configPathFile
	}
	yes, _ := FilePathExists(path)
	if yes {
		var err error
		conf, err = parseConfig(path)
		if err != nil {
			Trace("配置文件读取错误")
		} else {
			Trace("Config:")
			Trace(conf)
		}
	} else if path == "" {
		Trace("配置文件不存在!" + path)
	}
}

/**
返回配置对象
*/
func GetConfig() Config {
	return conf
}

//toml type
type mysqlConf struct {
	Host     string
	Port     string
	User     string
	Pswd     string
	Charset  string
	Database string
}

type redisConf struct {
	Host         string
	Port         string
	Pswd         string
	Database     string
	OrderInfo    string
	Orderlist    string
	Dealerlist   string
	Orderbidding string
	DealerInfo   string
	Timeout      int
}

type logConf struct {
	File  string
	Debug int
}

type thriftConf struct {
	Biddinghost string
}

type biddingConf struct {
	AddPrice int
}

type hammerConf struct {
	Interval   int
	TmpFile    string
	BidQue     string
	UnixSocket string
}

type Config struct {
	Mysql   mysqlConf
	Redis   redisConf
	Log     logConf
	Thrift  thriftConf
	Bidding biddingConf
	Hammer  hammerConf
}

type order struct {
	OrderId          int64   `json:"order_id"`
	BiddingStartTime string  `json:"bidding_start_time"`
	BidStartPrice    float64 `json:"bid_start_price"`
}

type orderBidding struct {
	DealerId    int64   `json:"dealer_id"`
	OrderId     int64   `json:"order_id"`
	BeforePrice float64 `json:"before_price"`
	AppendPrice float64 `json:"append_price"`
	AfterPrice  float64 `json:"after_price"`
	BiddingType int32   `json:"bidding_type"`
	CreateTime  int64   `json:"create_time"`
}

type orderDealer struct {
	DealerId   int64   `json:"dealer_id"`
	MaxPrice   float64 `json:"max_price"`
	BidCount   int64   `json:"bid_count"`
	CreateTime int64   `json:"create_time"`
}

/**
解析配置文件
*/
func parseConfig(cfg_file_path string) (c Config, err error) {
	var conf Config
	if _, err := toml.DecodeFile(cfg_file_path, &conf); err != nil {
		return conf, err
	} else {
		return conf, nil
	}

}
